package config

import (
	"fmt"
	"os"

	"gitee.com/eeppee_admin/go-tuiftp/reuse"
	"github.com/charmbracelet/bubbles/table"
	tea "github.com/charmbracelet/bubbletea"
)

// 创建站点配置
func Create(siteCfg *reuse.SiteConfig) {
	if _, err := tea.NewProgram(initialModel(siteCfg, nil)).Run(); err != nil {
		fmt.Printf("error: Failed to start program: %s", err)
		os.Exit(-1)
	}
}

// 列出配置站点, list arg
func List() {
	sysConfig := &reuse.SysConfig{}
	if err := sysConfig.Read(); err != nil {
		fmt.Printf("error: Failed to read config file: %s", err)
		os.Exit(-1)
	}

	showList(sysConfig.Sites)
}

// 编辑站点信息, edit arg
func Edit(name string) {
	// 1. app配置
	sysCfg := &reuse.SysConfig{}
	if err := sysCfg.Read(); err != nil {
		fmt.Printf("error: Failed to read config file: %s", err)
		os.Exit(-1)
	}
	// 2. 获取站点index
	var index *int
	for i, site := range sysCfg.Sites {
		if site.Name == name {
			index = &i
			break
		}
	}

	if index == nil {
		fmt.Printf("error: %s 没有在配置中\n", name)
		os.Exit(-1)
	}

	if _, err := tea.NewProgram(initialModel(&sysCfg.Sites[*index], index)).Run(); err != nil {
		fmt.Printf("error: Failed to start program: %s", err)
		os.Exit(-1)
	}
}

// 删除站点, delete arg
func Delete(name string) {
	sysCfg := &reuse.SysConfig{}
	if err := sysCfg.Read(); err != nil {
		fmt.Printf("error: Failed to read config file: %s", err)
		os.Exit(-1)
	}
	for i, site := range sysCfg.Sites {
		if site.Name == name {
			sysCfg.Sites[i] = sysCfg.Sites[len(sysCfg.Sites)-1]
			sysCfg.Sites = sysCfg.Sites[:len(sysCfg.Sites)-1]
			break
		}
	}
	sysCfg.Save()
	// 打开日志文件，返回错误而非直接终止
	if reuse.DebugMode {
		logFile, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			fmt.Printf("打开日志文件失败: %v", err) // 返回错误，让上层处理
		}
		defer logFile.Close()

		// 写入日志
		if _, err := logFile.WriteString("删除站点：" + name + "\n"); err != nil {
			fmt.Printf("写入日志失败: %v", err)
		}
	}
	fmt.Printf("delete site: %s", name)
}

// 展示站点信息
func showList(sites []reuse.SiteConfig) {
	var cols []table.Column

	if reuse.DebugMode {
		cols = append(cols,
			table.Column{Title: "名称", Width: 20},
			table.Column{Title: "类型", Width: 10},
			table.Column{Title: "主机地址", Width: 20},
			table.Column{Title: "端口", Width: 10},
			table.Column{Title: "账号", Width: 10},
			table.Column{Title: "密码", Width: 10},
		)
	} else {
		cols = append(cols,
			table.Column{Title: "名称", Width: 20},
			table.Column{Title: "类型", Width: 10},
			table.Column{Title: "主机地址", Width: 20},
			table.Column{Title: "端口", Width: 10},
			table.Column{Title: "账号", Width: 10},
		)
	}

	rows := make([]table.Row, len(sites))

	for i, site := range sites {
		// 调试查看密码
		if reuse.DebugMode {
			rows[i] = table.Row{
				site.Name,
				site.Type,
				site.Host,
				site.Port,
				site.Account,
				site.Password,
			}
		} else {
			rows[i] = table.Row{
				site.Name,
				site.Type,
				site.Host,
				site.Port,
				site.Account,
			}
		}
	}

	tableHeight := len(sites) + 2
	t := table.New(table.WithColumns(cols), table.WithRows(rows), table.WithFocused(true), table.WithHeight(tableHeight))
	fmt.Println(t.View())
}

// 这里创建配置站点文件
func createImpl(cfg *reuse.SiteConfig) error {
	sysCfg := new(reuse.SysConfig)
	if err := sysCfg.Read(); err != nil {
		return err
	}

	for _, site := range sysCfg.Sites {
		if site.Name == cfg.Name {
			return fmt.Errorf("站点名称已存在，请勿创建")
		}
	}

	sysCfg.Sites = append(sysCfg.Sites, *cfg)
	// 打开日志文件，返回错误而非直接终止
	if reuse.DebugMode {

		logFile, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			return fmt.Errorf("打开日志文件失败: %v", err) // 返回错误，让上层处理
		}
		defer logFile.Close()

		// 写入日志
		if _, err := logFile.WriteString("添加新站点：" + cfg.Name + "\n"); err != nil {
			return fmt.Errorf("写入日志失败: %v", err)
		}
	}
	return sysCfg.Save()

}

// 这里修改站点配置文件
func editImpl(cfg *reuse.SiteConfig, index *int) error {
	sysCfg := &reuse.SysConfig{}
	if err := sysCfg.Read(); err != nil {
		return err
	}

	sysCfg.Sites[*index] = *cfg
	// 打开日志文件，返回错误而非直接终止
	if reuse.DebugMode {
		logFile, err := os.OpenFile("app.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			return fmt.Errorf("打开日志文件失败: %v", err) // 返回错误，让上层处理
		}
		defer logFile.Close()

		// 写入日志
		if _, err := logFile.WriteString("修改新站点：" + cfg.Name + "\n"); err != nil {
			return fmt.Errorf("写入日志失败: %v", err)
		}
	}
	return sysCfg.Save()
}
